package vaccination;

import com.octo.captcha.module.servlet.image.SimpleImageCaptchaServlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import utils.DBController;
import utils.Utils;

/**
 * userID viene usato come cartina tornasole per segnalare gli errori
 * 
 * userID=1 username e passwrod attuali non sono corrette
 * userID=2 nuova username non disponibile
 * userID=3 nuova password non corretta
 * 
 * questa servlet crea un loop con se stessa fino a che tutti i dati sono stati inseriti
 * 
 * @author PacosHome
 */
public class Registration extends HttpServlet {
    private static Logger log = Logger.getLogger(Registration.class);
    @Override
    public void init() {
        PropertyConfigurator.configure(Registration.class.getClassLoader().getResource("utils/log4j.properties"));
    }

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        DBController dbController;
        String message = "";
        
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        //invalida la sessione
        request.getSession().invalidate();
        
        try {
            String typeUser = request.getParameter("typeUser");
            String name = request.getParameter("name");
            String surname = request.getParameter("surname");
            String year = request.getParameter("date_year");
            String month = request.getParameter("date_month");
            String day = request.getParameter("date_day");
            String old_username = request.getParameter("old_username");
            String new_username = request.getParameter("new_username");
            String old_password = request.getParameter("old_password");
            String new_password = request.getParameter("new_password");
            String new_password_cheak = request.getParameter("new_password_cheak");
            String userCaptchaResponse = request.getParameter("jcaptcha");
            
            int userID = 0;
            
            //se il captcha è esatto controllo i dati nel db
            if(name != null && surname != null){
                if(year != null || month != null || day != null) {
                    message = "Inserisci una data di nascita valida";
                }
                dbController = DBController.getInstance();
                userID = dbController.idRegistration(name, surname, year, month, day, typeUser, old_username, new_username,old_password, new_password, new_password_cheak);
                boolean captchaPassed = SimpleImageCaptchaServlet.validateResponse(request, userCaptchaResponse);
                
//                if(captchaPassed==false) {
//                    userID=4;
//                }
                
                if(userID>0) {
                    //errore nel modulo compilato e riscrittura pagina con segnalato l'errore !
                    //se user = 1 --> username non valido
                    //se user = 2 --> username già presente nel database
                    //se user = 3 --> errore nella password
                    //se user = 4 --> errore captcha

                    Utils.printHeader(request, out, "Registrazione");
                    out.println("                <form action=\"Registration\" method=\"post\">\n" +
                                "                        <div class=\"row-fluid show-grid\">\n" +
                                "                            <div class=\"span12\">\n" +
                                "                                <h1>Registrazione</h1>\n" +
                                "                                <br>\n" +
                                "                                <div class=\"alert alert-error span4\">\n" +
                                "                                     Ci sono stati degli errori. Ricontrolla.\n" +
                                "                                </div>\n" +
                                "                                <input type=\"hidden\" name=\"typeUser\" value="+typeUser+">\n" +
                                "                            </div>\n" +
                                "                        </div>\n" +
                                "                        <hr>\n" +
                                "                        <div class=\"row-fluid show-grid\">\n" +
                                "                            <div class=\"span4\">\n" +
                                "                                <h6>Nome Cognome</h6>\n" +
                                "                                <input type=\"text\" name=\"name\"  placeholder=\"name\"/>\n" +
                                "                                <br> \n" +
                                "                                <input type=\"text\" name=\"surname\"  placeholder=\"surname\"/>    \n" +
                                "                                <br>\n" +
                                "                                <h6>Data di nascita</h6>\n" +
                                "                                <input class=\"input-mini\" type=\"text\" maxlength=\"4\"  name=\"date_year\" placeholder=\"year\">\n" +
                                "                                <input class=\"input-mini\" type=\"text\" maxlength=\"2\" name=\"date_month\" placeholder=\"month\">\n" +
                                "                                <input class=\"input-mini\" type=\"text\" maxlength=\"2\" name=\"date_day\" placeholder=\"day\">\n" +
                                "                                <br>\n" +
                                "                            </div>\n");

                    //OLD username non giusto
                    if(userID==1) {

                    out.println("                            <div class=\"span4\">\n" +
                                "                                <h6>Username</h6>\n" +
                                "                                <div class=\"control-group error\">\n" +
                                "                                    <div class=\"controls\">\n" +
                                "                                        <label class=\"control-label\" for=\"inputError\">\n" +
                                "                                            <small>Non esiste un utente con questa user name e questa password</small>\n" +
                                "                                        </label>\n" +
                                "                                        <input type=\"text\" name=\"old_username\" id=\"inputError\" placeholder=\"username\"/>\n" +
                                "                                    </div>\n" +
                                "                                </div>\n" +
                                "                                <br>\n" +
                                "                                <small>Inserisci una nuova username<br>(se non vuoi cambiare lascia in bianco)</small>\n" +
                                "                                <input type=\"text\" name=\"new_username\" placeholder=\"\"/>\n" +
                                "                                <br>\n");    

                    //NEW username non disponibile 
                    } else if (userID==2) {

                    out.println("                            <div class=\"span4\">\n" +
                                "                                <h6>Username</h6>\n" +
                                "                                <input type=\"text\" name=\"old_username\" placeholder=\"username\"/> \n" +
                                "                                <br>\n" +
                                "                                <div class=\"control-group error\">\n" +
                                "                                    <div class=\"controls\">\n" +
                                "                                        <label class=\"control-label\" for=\"inputError\">\n" +
                                "                                            <small>segli un'altra username,<br>questa non è disponibile</small>\n" +
                                "                                        </label>\n" +
                                "                                        <input type=\"text\" name=\"new_username\" id=\"inputError\" placeholder=\"\"/> \n" +
                                "                                    </div>\n" +
                                "                                </div>\n"); 

                    //username tutto OK
                    } else {

                    out.println("                            <div class=\"span4\">\n" +
                                "                                <h6>Username</h6>\n" +
                                "                                <input type=\"text\" name=\"old_username\" placeholder=\"username\"/> \n" +
                                "                                <br>\n" +
                                "                                <small>Inserisci una nuova username<br>(se non vuoi cambiare lascia in bianco)</small>\n" +
                                "                                <input type=\"text\" name=\"new_username\" placeholder=\"\"/> \n" +
                                "                                <br>\n");

                    }

                    if(userID==1) {

                    out.println("                                <h6>Password</h6>\n" +
                                "                                <div class=\"control-group error\">\n" +
                                "                                    <div class=\"controls\">\n" +
                                "                                        <input type=\"password\" name=\"old_password\" id=\"inputError\" placeholder=\"password\"/>\n" +
                                "                                    </div>\n" +
                                "                                </div>\n" +
                                "                                <small>Inserisci una nuova password<br>(se non vuoi cambiare lascia in bianco)</small>\n" +
                                "                               <input type=\"password\" name=\"new_password\" placeholder=\"\"/>\n" +
                                "                                <br>\n" +
                                "                               <small>Reinserisci la nuova password</small>\n" +
                                "                                <input type=\"password\" name=\"new_password_cheak\" placeholder=\"\"/>\n" +
                                "                            </div>\n");

                    } else if(userID==2) {

                    out.println("                                <h6>Password</h6>\n" +
                                "                                <input type=\"password\" name=\"old_password\" placeholder=\"password\"/>\n" +
                                "                                 <div class=\"control-group error\">\n" +
                                "                                    <div class=\"controls\">\n" +
                                "                                        <label class=\"control-label\" for=\"inputError\">\n" +
                                "                                            <small>Non hai compilato correttamente<br>inserisci la nuova password</small>\n" +
                                "                                        </label>\n" +
                                "                                        <input type=\"password\" name=\"new_password\" id=\"inputError\" placeholder=\"\"/>\n" +
                                "                                        <br><small>Reinserisci la nuova password</small>\n" +
                                "                                        <input type=\"password\" name=\"new_password_cheak\" id=\"inputError\" placeholder=\"\"/> \n" +
                                "                                    </div>\n" +
                                "                                </div>\n" +
                                "                            </div>\n");

                    } else {

                    out.println("                                <h6>Password</h6>\n" +
                                "                                <input type=\"password\" name=\"old_password\" placeholder=\"password\"/>\n" +
                                "                                <br>\n" +
                                "                                <small>Inserisci una nuova password<br>(se non vuoi cambiare lascia in bianco)</small>\n" +
                                "                                <input type=\"password\" name=\"new_password\" placeholder=\"\"/>\n" +
                                "                                <br>\n" +
                                "                                <small>Reinserisci la nuova password</small>\n" +
                                "                                <input type=\"password\" name=\"new_password_cheak\" placeholder=\"\"/> \n" +
                                "                            </div>\n");
                    }

                    if(userID==4) {

                     out.println("                                <h6>Password</h6>\n" +
                                "                                <input type=\"password\" name=\"old_password\" placeholder=\"password\"/>\n" +
                                "                                <br>\n" +
                                "                                <small>Inserisci una nuova password<br>(se non vuoi cambiare lascia in bianco)</small>\n" +
                                "                                <input type=\"password\" name=\"new_password\" placeholder=\"\"/>\n" +
                                "                                <br>\n" +
                                "                                <small>Reinserisci la nuova password</small>\n" +
                                "                                <input type=\"password\" name=\"new_password_cheak\" placeholder=\"\"/> \n" +
                                "                            </div>\n");
                    
                    } else {

                    out.println("                            <div class=\"span4\">\n" +
                                "                                <h6>Inserisci la parola qui sotto</h6>\n" +
                                "                                <img src=\"jcaptcha.jpg\" /> <br><br>\n" +
                                "                                <input type=\"text\" name=\"jcaptcha\" value=\"\" placeholder=\"captcha\"/>\n" +
                                "                                <br>\n"+ 
                                "                           </div>\n");
                    }

                    out.println("                        </div>\n" +
                                "                        <div class=\"row-fluid show-grid\">\n" +
                                "                            <div class=\"span12\">\n" +
                                "                                <button class=\"btn btn-primary\" type=\"submit\">Registrati</button>\n" +
                                "                                &nbsp;&nbsp;\n" +
                                "                                <a href=\"javascript:history.back()\">\n" +
                                "                                    <button class=\"btn btn-primary\">Back</button> \n" +
                                "                                </a>\n" +
                                "                            </div>\n" +
                                "                        </div>\n" +
                                "                </form>\n");
                    Utils.printFooter(out);

                } else {
                    // se la registrazione è andata a buon fine 
                    message = name+" "+surname+", la tua registrazione è stata effettuata con successo! "  +
                            "<br>" +
                            "<br>" +
                            "<a href=\"login.html\">\n" +
                            "<button class=\"btn btn-primary btn-success\">Login</button> \n" +
                            "</a>";
                    Utils.printHeader(request, out, "Registrazione");
                    Utils.printSuccess(request, out, message);
                    Utils.printFooter(out);
                    return;
                }                
            }
            
        } catch(Exception e){
            //stampa tramite log4j il messaggio dell'eccezione e restituisce la pagina di errore
            log.error(e.getMessage());
            String typeUser = request.getParameter("typeUser");
            
            if(message.equals("")) {
                
                if(typeUser.equals("patient")){
                    message = e.getMessage()+"" +
                        "<br>" +
                        "<br>" + 
                        "<a href=\"paziente_registration.html\">\n" +
                        "<button class=\"btn btn-primary btn-error\">Back</button>\n" +
                        "</a>";
                }else{
                    message = e.getMessage()+"" +
                        "<br>" +
                        "<br>" + 
                        "<a href=\"dottore_registration.html\">\n" +
                        "<button class=\"btn btn-primary btn-error\">Back</button>\n" +
                        "</a>";
                }
            } else {
                
                if(typeUser.equals("patient")){
                    message = e.getMessage()+"<br>"
                            + ""+message+"" +
                        "<br>" +
                        "<br>" + 
                        "<a href=\"paziente_registration.html\">\n" +
                        "<button class=\"btn btn-primary btn-error\">Back</button>\n" +
                        "</a>";
                }else{
                    message = e.getMessage()+"<br>"
                            + ""+message+"" +
                        "<br>" +
                        "<br>" + 
                        "<a href=\"dottore_registration.html\">\n" +
                        "<button class=\"btn btn-primary btn-error\">Back</button>\n" +
                        "</a>";
                }
            }
            
            
            
            Utils.printHeader(request, out, "Registrazione");
            Utils.printError(request, out, message);
            Utils.printFooter(out);
            
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

